import mimetypes
from dataclasses import dataclass
from typing import List, Optional

from mutagen.flac import FLAC, Picture
from mutagen.flac import VCFLACDict

@dataclass
class UpdateMetadataParams:
    audio: str
    meta: 'AudioMeta'
    album_art: Optional[bytes] = None
    album_art_ext: Optional[str] = None

@dataclass
class AudioMeta:
    title: str
    album: str
    artists: List[str]

def update_meta_flac(out_path: str, params: UpdateMetadataParams, logger) -> None:
    audio = FLAC(params.audio)
    audio.clear()

    if params.meta.title:
        audio["title"] = params.meta.title
    if params.meta.album:
        audio["album"] = params.meta.album
    if params.meta.artists:
        audio["artist"] = params.meta.artists

    if params.album_art:
        cover_mime = mimetypes.guess_type(params.album_art_ext)[0]
        logger.debug("cover image mime detect", mime=cover_mime)
        picture = Picture()
        picture.data = params.album_art
        picture.type = Picture.FRONT_COVER
        picture.mime = cover_mime
        audio.add_picture(picture)

    audio.save(out_path)
